<template>
  <div class="mind-map-summary-container">
    <van-empty v-if="isEmpty" description="暂无内容" />
    <template v-else>
      <div class="tc_btns">
        <div class="tc_btn" @click="handleCopy">
          <img src="@/icons/svg/minute/copy_icon.svg" />
        </div>
        <div class="tc_btn" @click="toggleFullscreen">
          <img src="@/icons/svg/minute/fullscreen.svg" />
        </div>
      </div>
      <div class="markmap-view">
        <MarkmapRender ref="refMarkmap" :content="markdownContent" />
      </div>
    </template>

    <!-- 全屏模式使用 Teleport -->
    <Teleport to="body" v-if="isFullscreen">
      <div class="fullscreen-overlay" @click="handleOverlayClick">
        <div class="fullscreen-container" @click.stop>
          <div class="fullscreen-header">
            <div class="left-btns">
              <div class="tc_btn" @click="handleCopy">
                <img src="@/icons/svg/minute/copy_icon.svg" />
                <span>复制</span>
              </div>
            </div>
            <div class="tc_btn close-btn" @click="toggleFullscreen">
              <img src="@/icons/svg/minute/close.svg" />
            </div>
          </div>
          <div class="fullscreen-content">
            <MarkmapRender ref="refMarkmapFullscreen" :content="markdownContent" />
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script>
import { mapState } from "pinia";
import { useMinutesStore } from "@/store";
import { showToast } from "vant";
import "vant/es/toast/style";
import MarkmapRender from "./MarkmapRender.vue";
import { addToClipboard } from "/src/utils/stringTool.js";

export default {
  name: "MindMapSummary",
  components: { MarkmapRender },

  data() {
    return {
      isFullscreen: false
    };
  },

  mounted() {
    this.addKeyboardListener();
  },

  beforeUnmount() {
    this.removeKeyboardListener();
  },

  computed: {
    isEmpty() {
      return !this.mindMapSummaryInfo;
    },
    ...mapState(useMinutesStore, {
      mindMapSummaryInfo: "mindMapSummary"
    }),

    markdownContent() {
      if (this.isEmpty) return "";
      return this.convertToMarkdown(this.mindMapSummaryInfo);
    }
  },

  methods: {
    convertToMarkdown(array, level = 1) {
      let markdown = "";
      for (const item of array) {
        markdown += "#".repeat(level) + " " + item.Title + "\n\n";
        if (item.Topic) {
          markdown += this.convertToMarkdown(item.Topic, level + 1);
        }
      }
      return markdown;
    },

    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      this.$nextTick(() => {
        if (this.isFullscreen) {
          this.$refs.refMarkmapFullscreen?.renderMarkmap();
        } else {
          this.$refs.refMarkmap?.renderMarkmap();
        }
      });
    },

    handleOverlayClick() {
      this.toggleFullscreen();
    },

    addKeyboardListener() {
      document.addEventListener('keydown', this.handleKeydown);
    },

    removeKeyboardListener() {
      document.removeEventListener('keydown', this.handleKeydown);
    },

    handleKeydown(event) {
      if (event.key === 'Escape' && this.isFullscreen) {
        this.toggleFullscreen();
      }
    },

    handleCopy() {
      if (this.isEmpty) return;
      const convertToText = (array, level = 0) => {
        let text = "";
        for (const item of array) {
          text += "  ".repeat(level) + "- " + item.Title + "\n";
          if (item.Topic) {
            text += convertToText(item.Topic, level + 1);
          }
        }
        return text;
      };

      const plainText = convertToText(this.mindMapSummaryInfo);

      addToClipboard(plainText);
      showToast("复制成功");
    },

    handleSave() {
      const markmapRef = this.isFullscreen ? this.$refs.refMarkmapFullscreen : this.$refs.refMarkmap;
      const svg = markmapRef.$el.querySelector("svg");
      if (!svg) {
        showToast("无法获取思维导图内容");
        return;
      }

      try {
        // 获取 SVG 的实际尺寸
        const svgRect = svg.getBoundingClientRect();
        const width = svgRect.width || 800;
        const height = svgRect.height || 600;

        const svgData = new XMLSerializer().serializeToString(svg);
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        const img = new Image();

        // 设置画布大小
        canvas.width = width;
        canvas.height = height;

        img.onload = () => {
          ctx.fillStyle = "white";
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0);

          // 下载图片
          const link = document.createElement("a");
          link.download = "思维导图.png";
          link.href = canvas.toDataURL("image/png");
          link.click();
          showToast("保存成功");
        };

        img.onerror = () => {
          showToast("保存失败");
        };

        img.src = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData)));
      } catch (error) {
        console.error("保存思维导图时出错:", error);
        showToast("保存失败");
      }
    }
  }
};
</script>

<style lang="less" scoped>
.mind-map-summary-container {
  margin-top: 12px;
  padding: 0 15px;
  height: calc(100vh - 182px);
  position: relative;

  .tc_btns {
    display: flex;
    justify-content: right;
    margin-bottom: 10px;

    .tc_btn {
      margin: 0 10px;
      color: #8c8c8c;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        opacity: 0.8;
      }

      img {
        width: 20px;
        height: 20px;
        vertical-align: middle;
      }
    }
  }

  .markmap-view {
    width: 100%;
    height: calc(100vh - 120px);
  }
}

// 全屏样式
.fullscreen-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.85);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: fadeIn 0.3s ease-out;
  backdrop-filter: blur(4px);
}

.fullscreen-container {
  width: 100%;
  height: 100%;
  background: white;
  display: flex;
  flex-direction: column;
  animation: slideIn 0.3s ease-out;
}

.fullscreen-header {
  height: 60px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  flex-shrink: 0;

  .left-btns {
    display: flex;
    gap: 16px;
  }

  .center-tip {
    flex: 1;
    text-align: center;
    
    span {
      font-size: 12px;
      color: #999;
      background: rgba(0, 0, 0, 0.05);
      padding: 4px 12px;
      border-radius: 12px;
    }
  }

  .tc_btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
    color: #606266;

    &:hover {
      background-color: #f5f5f5;
      transform: translateY(-1px);
    }

    img {
      width: 20px;
      height: 20px;
    }

    span {
      font-size: 14px;
      font-weight: 500;
    }
  }

  .close-btn {
    padding: 8px;
    border-radius: 50%;
    
    &:hover {
      background-color: #f5f5f5;
    }
  }
}

.fullscreen-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
